package com.xm9m.ibczy.mytest.alimama.mobile.demo;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.alimama.mobile.sdk.MmuSDK;
import com.alimama.mobile.sdk.config.FeedController;
import com.alimama.mobile.sdk.config.FeedProperties;
import com.alimama.mobile.sdk.config.MmuSDKFactory;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xm9m.ibczy.mytest.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
 * Created by jhenxu on 14-12-16.
 */
public class FeedViewActivity extends BaseActivity implements MockDataListener, FeedController.IncubatedListener {
    IterSlot iterSlot = new IterSlot();
    FeedController mController;
    MmuSDK mmuSDK;
    PullToRefreshListView mList;
    View loadView;
    List<Object> mItems = new ArrayList<Object>();
    int onLoading = 0;//1：刷新 2：加载 0：无操作
    String[] mSlotId = new String[2];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.taobao_example_xp_feeds);
        setTitle("信息流");

        mList = (PullToRefreshListView) findViewById(R.id.list);

        // Set a listener to be invoked when the list should be refreshed.
        mList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (0 == refreshView.getRefreshableView().getFirstVisiblePosition()) {
                    reflush();
                } else {
                    loadMore();
                }

            }
        });

        mList.setMode(PullToRefreshBase.Mode.BOTH);
        loadView = findViewById(R.id.loading);

        final ImageCache iCache = new ImageCache();
        mList.setAdapter(new FeedsAdapter(this, mItems, iCache));

        mmuSDK = MmuSDKFactory.getMmuSDK();
        mmuSDK.accountServiceInit(this);
        mmuSDK.init(getApplication());//初始化SDK,该方法必须保证在集成代码前调用，可移到程序入口处调用
        mController = FeedProperties.getMmuController();//如果插件加载失败，将返回null，在使用controller请都先判空
        if (mController != null) {
            mController.setIncubatedListener(this);//设置Feed初始化过程的监听
        }

        reflush();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void reflush() {
        if (0 == onLoading) {
            onLoading = 1;
            requestMockItem(this);
        } else {
            Toast.makeText(this, "正在加载中，请稍后...", Toast.LENGTH_SHORT).show();
            mList.onRefreshComplete();
        }

    }

    private void loadMore() {
        if (0 == onLoading) {
            onLoading = 2;
            requestMockItem(this);
        } else {
            Toast.makeText(this, "正在加载中，请稍后...", Toast.LENGTH_SHORT).show();
            mList.onRefreshComplete();
        }
    }

    /**
     * 模拟获取一般Item的网络操作
     *
     * @return
     */
    public void requestMockItem(final MockDataListener listener) {
        //每次页面数据发生变化时进行Feed数据初始化
        mSlotId[0] = iterSlot.iterlator();
        mSlotId[1] = iterSlot.iterlator();

        FeedProperties prop = new FeedProperties(mSlotId[0]);
        mmuSDK.attach(prop);
        FeedProperties prop_b = new FeedProperties(mSlotId[1]);
        mmuSDK.attach(prop_b);

        new AsyncTask<Void, Void, Integer[]>() {

            @Override
            protected Integer[] doInBackground(Void... params) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return new Integer[]{0, 0, 0, 0};
            }

            @Override
            protected void onPostExecute(Integer[] integers) {
                if (listener != null) {
                    listener.onReviced(integers);
                }
            }
        }.execute();
    }

    @Override
    public void onReviced(Integer[] data) {
        if (1 == onLoading) {
            mItems.clear();
        }

        FeedController.MMFeed a = null, b = null;

        if (mController != null) {
            a = (TextUtils.isEmpty(mSlotId[0])) ? null : mController.getProduct(mSlotId[0]);
            b = (TextUtils.isEmpty(mSlotId[1])) ? null : mController.getProduct(mSlotId[1]);
            if (a == null) {
                Log.i("Feeds", String.format("###推广位[%s]获取数据失败，将无法获取Feed.", mSlotId[0]));
            } else {
                Log.i("Feeds", String.format("###推广位[%s]获取成功", mSlotId[0]));
            }
            if (b == null) {
                Log.i("Feeds", String.format("###推广位[%s]获取数据失败，将无法获取Feed.", mSlotId[1]));
            } else {
                Log.i("Feeds", String.format("###推广位[%s]获取成功", mSlotId[1]));
            }
            mSlotId[0] = "";
            mSlotId[1] = "";

        }

        for (int i = 0; i < data.length; i++) {
            mItems.add(i);
            if (i == 1 && a != null && a.isReady()) {
                mItems.add(a);
            }

            if (i == 3 && b != null && b.isReady()) {
                mItems.add(b);
            }
        }


        ListAdapter adapter = mList.getRefreshableView().getAdapter();
        ((BaseAdapter) ((HeaderViewListAdapter) adapter).getWrappedAdapter()).notifyDataSetChanged();

        if (View.VISIBLE == loadView.getVisibility()) {
            loadView.setVisibility(View.GONE);
        }

        mList.onRefreshComplete();

        onLoading = 0;//reset loading status
    }

    @Override
    public void onComplete(int status, String slot) {
        try {
            if (0 == status) {
                Log.i("Feeds", String.format("推广位[%s]获取数据失败，将无法获取Feed.", slot));
            } else if (1 == status) {
                Log.i("Feeds", String.format("推广位[%s]的实时数据已经准备好", slot));
            } else if (2 == status) {
                Log.i("Feeds", String.format("推广位[%s]的缓存数据已经准备好", slot));
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onClick() {
        Toast.makeText(this,"onClick",1).show();
    }

    static class FeedsAdapter extends BaseAdapter {
        FeedViewActivity activity;
        ImageCache iCache;
        List<Object> mOccupied;
        Map<Integer, View> feedCache = new HashMap<Integer, View>();

        public FeedsAdapter(FeedViewActivity ac, List<Object> l, ImageCache iCache) {
            super();
            this.activity = ac;
            this.iCache = iCache;
            mOccupied = l;
        }

        @Override
        public int getCount() {
            return mOccupied.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Object object = mOccupied.get(position);
            if (object instanceof FeedController.MMFeed) {
                if (feedCache.containsKey(position)) {
                    View view = feedCache.get(position);
                    ViewGroup p = (ViewGroup) view.getParent();
                    if (p != null) {
                        p.removeView(view);
                    }
                    return view;
                } else {
                    FeedController.MMFeed feed = (FeedController.MMFeed) object;
                    ViewGroup fv = (ViewGroup) View.inflate(activity, R.layout.taobao_example_xp_feeds_item_shell, null);

//                    //使用默认模板创建FeedView
//                    FeedViewFactory.context = activity.getApplicationContext();
//                    FeedViewFactory.setmClickErrorListener(new ClickErrorListener() {
//
//                        @Override
//                        public void onClickPromoterError() {
//                            Toast.makeText(activity, "网络失败，请检查网络", Toast.LENGTH_SHORT).show();
//                        }
//                    });
                    View feedView = activity.mController.getFeedView(activity, feed);
                    fv.addView(feedView);
                    fv.setTag("FeedView");
                    feedCache.put(position, fv);//缓存已经显示过的FeedView

//                    //自定义View
//                    List<Promoter> promoters = feed.getPromoters();
//                    if(promoters != null && promoters.size() > 0) {
//                        Promoter usePromoter = promoters.get(0);
//                        feed.getDataService(activity).reportImpression(usePromoter);//发送展示report 否则将无展示pv
//                        //根据promoter 创建View
//                        //...
//                    }

                    return fv;
                }
            } else {
                View view;
                if (convertView == null || (convertView.getTag() != null && convertView.getTag().equals("FeedView"))) {
                    view = View.inflate(activity, R.layout.taobao_example_xp_feeds_item, null);
                    ((ImageView) view.findViewById(R.id.image)).setImageResource(iCache.iterlator());
                } else {
                    view = convertView;
                    ((ImageView) view.findViewById(R.id.image)).setImageResource(iCache.iterlator());
                }

                return view;
            }
        }
    }

    /**
     * MockData
     */
    static class ImageCache {
        Stack<Integer> cacheA = new Stack<Integer>();
        Stack<Integer> cacheB = new Stack<Integer>();
        int cusor = 0;// %2==0 ? cacheA : cacheB

        public ImageCache() {
//            cacheA.push(R.drawable.taobao_xp_example_feeds_imga);
//            cacheA.push(R.drawable.taobao_xp_example_feeds_imgb);
//            cacheA.push(R.drawable.taobao_xp_example_feeds_imgc);
//            cacheA.push(R.drawable.taobao_xp_example_feeds_imgd);
            cacheA.push(R.drawable.taobao_xp_example_feeds_imge);
//            cacheA.push(R.drawable.taobao_xp_example_feeds_imgf);
            cacheA.push(R.drawable.taobao_xp_example_feeds_imgg);
            cacheA.push(R.drawable.taobao_xp_example_feeds_imgh);
//            cacheA.push(R.drawable.taobao_xp_example_feeds_imgi);
            cusor = 0;
        }

        public synchronized int iterlator() {
            Stack<Integer> dumpCache = cusor % 2 == 0 ? cacheA : cacheB;
            Stack<Integer> pushCache = cusor % 2 == 0 ? cacheB : cacheA;

            Integer integer = dumpCache.pop();
            pushCache.push(integer);

            if (dumpCache.size() == 0) cusor++;

            return integer;
        }
    }

    /**
     * 推广位轮流拾取容器
     */
    static class IterSlot {

        Stack<String> cacheA = new Stack<String>();
        Stack<String> cacheB = new Stack<String>();
        int cusor = 0;// %2==0 ? cacheA : cacheB

        public IterSlot() {
//            public static String SLOT_FEED_IMG_ITEM = "60466";
//            public static String SLOT_FEED_SMALLIMG_APP = "60487";
//            public static String SLOT_FEED_SMALLIMG_ITEM = "60488";
//            public static String SLOT_FEED_ICON_ITEM = "54354";
//            public static String SLOT_FEED_ICON_APP = "55280";
            cacheA.push("60466");
//            cacheA.push("60487");
            cacheA.push("60488");
            cacheA.push("54354");
//            cacheA.push("55280");
            cusor = 0;
        }

        public synchronized String iterlator() {
            Stack<String> dumpCache = cusor % 2 == 0 ? cacheA : cacheB;
            Stack<String> pushCache = cusor % 2 == 0 ? cacheB : cacheA;

            String integer = dumpCache.pop();
            pushCache.push(integer);

            if (dumpCache.size() == 0) cusor++;

            return integer;
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (!mmuSDK.accountServiceHandleResult(requestCode, resultCode, data,this)) {
			super.onActivityResult(requestCode, resultCode, data);
		}
    }

}
